package com.core.async;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.core.interfaces.IMessageExecutorPool;

public class ApplicationContext {

	/** 异步操作线程池 **/
	protected ThreadPoolExecutor asyncExecutor = null;

	/** 主线程池 **/
	protected IMessageExecutorPool mainExecutor = null;

	/** 异步线程数 **/
	protected static int asyncExecutor_thread_num = (Runtime.getRuntime().availableProcessors() / 2);

	// status map
	protected static Map<String, Long> statMap = new HashMap<String, Long>(3);

	public void init(IMessageExecutorPool mainExecutor, ThreadPoolExecutor asyncExecutor) {
		this.asyncExecutor = asyncExecutor;
		this.mainExecutor = mainExecutor;
	}

	public void init(IMessageExecutorPool mainExecutor) {
		if(asyncExecutor==null)
		{
			this.asyncExecutor = new ThreadPoolExecutor(asyncExecutor_thread_num,
					asyncExecutor_thread_num, 0L, TimeUnit.MILLISECONDS,
					new PriorityBlockingQueue<Runnable>(),new ThreadFactory() {
				@Override
				public Thread newThread(Runnable r) {
					Thread thread = new Thread(r);
					thread.setName("async Thread");
					return thread;
				}
			});
		}
		this.mainExecutor = mainExecutor;
	}
	
	public void shutDown()
	{
		if(asyncExecutor!=null&&!asyncExecutor.isShutdown())
			asyncExecutor.shutdown();
		if(mainExecutor!=null)
			mainExecutor.shutDown();
	}
}
